package com.google.code.jcooky.rpc.compiler.java;

import static com.google.code.jcooky.rpc.compiler.StringUtils.copyOfString;
import static com.google.code.jcooky.rpc.compiler.StringUtils.read;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.code.jcooky.rpc.compiler.Processor;

public class JavaEnumProcessor extends Processor {
	
	private String enum_layout, enum_entries_layout, enum_valueof_layout;

	public JavaEnumProcessor() throws IOException {
		super();
		
		enum_layout = read("enum.layout");
		enum_entries_layout = read("enum_entries.layout");
		enum_valueof_layout = read("enum_valueof.layout");
	}

	@Override
	public void process(Map<String, Object> attr) throws ProcessException {
		String src = copyOfString(enum_layout);
		
		List<Map<String, Object>> entries = (List<Map<String, Object>>)attr.get("entries");
		src = src.replace("%namespace%", getNamespace());
		src = src.replaceAll("%enum_name%", (String)attr.get("enum_name"));
		src = src.replace("%enum_entries.layout%", getEnumEntries(entries));
		src = src.replace("%enum_valueof.layout%", getEnumValueof(entries));
		
		write(src, (String)attr.get("enum_name"));
	}
	
	private String getEnumEntries(List<Map<String, Object>> attr) {
		StringBuffer strbuf = new StringBuffer(256);
		Iterator<Map<String, Object>> it = attr.iterator();
		while(it.hasNext()) {
			Map<String, Object> m = it.next();
			String src = copyOfString(enum_entries_layout);
			src = src.replace("%key%", (String)m.get("key"));
			src = src.replace("%value%", m.get("value").toString());
			strbuf.append(src);
			if(it.hasNext())
				strbuf.append(",");
			else
				strbuf.append(";");
		}
		return strbuf.toString();
	}
	
	private String getEnumValueof(List<Map<String, Object>> attr) {
		StringBuffer strbuf = new StringBuffer(256);
		for(Map<String, Object> m : attr) {
			String src = copyOfString(enum_valueof_layout);
			src = src.replace("%key%", (String)m.get("key"));
			src = src.replace("%value%", m.get("value").toString());
			strbuf.append(src).append("\n");
		}
		return strbuf.toString();
	}
}
